package com.jiang.专题.动态规划.Q1964;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/01/14 16:08
 */
class Solution {
    // 动态规划（超时）
    // public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {
    //     int len = obstacles.length;
    //     int[] dp = new int[len]; // dp[i] 表示 在i位置的最长有效障碍路线
    //     Arrays.fill(dp, 1);
    //     for (int i = 1; i < len; i++) {
    //         for (int j = 0; j < i; j++) {
    //             if (obstacles[i] >= obstacles[j]) {
    //                 dp[i] = Math.max(dp[i], dp[j] + 1);
    //             }
    //         }
    //     }
    //     return dp;
    // }

    // 贪心 + 二分查找
    public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {
        int len = obstacles.length;
        int[] res = new int[len];
        res[0] = 1;

        List<Integer> list = new ArrayList<>();
        list.add(obstacles[0]);
        for (int i = 1; i < len; i++) {
            int high = obstacles[i];
            int high_len = -1; // 第i个位置的最长有效障碍路线
            if (high >= list.get(list.size() - 1)) {
                list.add(high);
                high_len = list.size();
            } else {
                int index = binarySearch(list, high);
                list.set(index, high);
                high_len = index + 1;
            }
            res[i] = high_len;
        }
        return res;
    }

    // 二分查找 high 应放到第一个比high大于的位置
    private int binarySearch(List<Integer> list, int high) {
        int l = 0, r = list.size() - 1;
        while (l < r) {
            int mid = (r - l) / 2 + l;
            if (list.get(mid) > high) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        return l;
    }
}
